import 'package:common_utils/common_utils.dart';
import 'package:erp/data/api/process_api.dart';
import 'package:erp/data/model/process_file.dart';
import 'package:erp/data/model/process_node.dart';
import 'package:erp/data/model/process_type.dart';
import 'package:erp/data/model/sale_project_detail.dart';
import 'package:erp/modules/process_center/controller.dart';
import 'package:erp/routes/app_pages.dart';
import 'package:erp/util/app_utils.dart';
import 'package:erp/widgets/form1/form_builder.dart';
import 'package:erp/widgets/process_attachment_upload.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

class SaleProjectApplyController extends GetxController {
  final FormManagement formManagement1 = FormManagement();
  final ScrollController scrollController = ScrollController();

  final Map<String, dynamic> formData = {};
  final List<SaleProjectDetail> saleProjectDetails = [];
  final List<ProcessAttachment> processFiles = [];
  List<ProcessNode> processNodeList = [];

  final Map<String, dynamic> process = {};

  final List<FilterChipItem> docListItems = [
    FilterChipItem(label: Text('设计概算'), data: '1'),
    FilterChipItem(label: Text('施工图纸'), data: '2'),
    FilterChipItem(label: Text('总包投标报价清单'), data: '3'),
    FilterChipItem(label: Text('招标文件'), data: '4'),
    FilterChipItem(label: Text('施工量清单'), data: '5'),
    FilterChipItem(label: Text('技术要求'), data: '6'),
  ];

  @override
  void onInit() async {
    if (Get.arguments['processType'] != null) {
      process["typeCode"] = (Get.arguments['processType'] as ProcessType).typeCode;
    } else {
      var data = Get.arguments['data'];
      process.addAll(data["process"]);
      processFiles.addAll(
        (data['processFileList'] as List)
            .map((e) => ProcessFile.fromJson(e))
            .map(
              (f) => ProcessAttachment(
                id: f.id,
                path: f.fileUrl,
                name: f.fileName,
              ),
            )
            .toList(),
      );
      var object = data['object'];
      saleProjectDetails.addAll(
        (object['saleProjectDetailList'] as List).map((e) => SaleProjectDetail.fromJson(e)).toList(),
      );
      formData['docList'] = (object['saleProjectDocList'] as List).map((e) => e['docCode']).toList();
      formData.addAll(object['saleProject']);
    }

    super.onInit();
  }

  @override
  void dispose() {
    super.dispose();
    scrollController.dispose();
  }

  /// 保存为待办
  void saveToBeTodo() async {
    var validateResult1 = formManagement1.validate();
    if (!validateResult1.result) {
      EasyLoading.showError(validateResult1.message ?? "");
      RenderBox box = validateResult1.globalKey!.currentContext!.findRenderObject() as RenderBox;
      scrollController.position.ensureVisible(box, duration: Duration(milliseconds: 1000), curve: Curves.ease);
      return;
    }
    Map<String, dynamic> dataMap = formManagement1.data;
    formData.addAll(dataMap);
    List<dynamic> docValueList = formData.remove('docList');
    var dto = {
      'type': 1,
      'process': process,
      'object': {
        'saleProject': formData,
        'saleProjectDetailList': saleProjectDetails,
        'saleProjectDocList': docListItems
            .where((element) => docValueList.contains(element.data))
            .map((e) => {'docName': (e.label as Text).data, 'docCode': e.data})
            .toList(),
      },
      'processNodeList': processNodeList,
    };
    List<String> paths = processFiles.where((element) => (element.id == null)).map((e) => e.path ?? '').toList();
    await ProcessApi.applyProcess(JsonUtil.encodeObj(dto)!, paths);
    Get.back();
  }

  /// 提交申请
  void submit() async {
    var validateResult1 = formManagement1.validate();
    if (!validateResult1.result) {
      EasyLoading.showError(validateResult1.message ?? "");
      RenderBox box = validateResult1.globalKey!.currentContext!.findRenderObject() as RenderBox;
      scrollController.position.ensureVisible(box, duration: Duration(milliseconds: 1000), curve: Curves.ease);
      return;
    }

    var data = await ProcessApi.getProcessNodeRangeInfo(process["typeCode"] ?? "");
    var result = await Get.toNamed(Routes.PROCESS_NODE_CHOOSE, arguments: {'data': data});
    if (result == null) {
      return;
    }

    processNodeList = result['processNodeList'];
    Map<String, dynamic> dataMap = formManagement1.data;
    formData.addAll(dataMap);
    List<dynamic> docValueList = formData.remove('docList');
    var dto = {
      'type': 2,
      'process': process,
      'object': {
        'saleProject': formData,
        'saleProjectDetailList': saleProjectDetails,
        'saleProjectDocList': docListItems
            .where((element) => docValueList.contains(element.data))
            .map((e) => {'docName': (e.label as Text).data, 'docCode': e.data})
            .toList(),
      },
      'processNodeList': processNodeList,
    };
    List<String> paths = processFiles.where((element) => element.id == null).map((e) => e.path ?? '').toList();
    AppUtils.confirm(
      content: "是否确定提交？",
      confirmCallback: () async {
        await ProcessApi.applyProcess(JsonUtil.encodeObj(dto)!, paths);
        Get.back();
        var flowCenterController = Get.find<FlowCenterController>();
        flowCenterController.tabController.animateTo(2);
      },
    );
  }

// 编辑项目详情
  Future<bool> editProjectDetail(int index) async {
    var item = saleProjectDetails[index];
    var result = await Get.toNamed(Routes.SALE_PROJECT_DETAILS, arguments: {'data': item.toJson()});
    if (result != null) {
      SaleProjectDetail detail = SaleProjectDetail.fromJson(result['data']);
      if (item != detail) {
        saleProjectDetails[index] = detail;
        return true;
      }
      return false;
    } else {
      return false;
    }
  }

  Future<bool> addProjectDetail() async {
    var result = await Get.toNamed(Routes.SALE_PROJECT_DETAILS, arguments: {});
    if (result != null) {
      SaleProjectDetail detail = SaleProjectDetail.fromJson(result['data']);
      saleProjectDetails.add(detail);
      return true;
    } else {
      return false;
    }
  }

// 10MB
  final int max_single_file_size = 10485760;

// 50MB
  final int max_all_file_size = 52428800;

  Future<bool> uploadFiles(FilePickerResult? result) async {
    var totalSize =
        processFiles.map((element) => element.size ?? 0).toList().fold(0, (value, element) => (value as int) + element);
    if (result != null) {
      for (var file in result.files) {
        if (processFiles.any((element) => element.path == file.path && element.name == file.name)) {
          continue;
        }
        if ((file.size) > max_single_file_size) {
          EasyLoading.showError('单个文件不能超过10M');
          return false;
        }

        if ((file.size + totalSize) > max_single_file_size) {
          EasyLoading.showError('文件总大小不能超过50M');
          return false;
        }
        processFiles.add(ProcessAttachment(
          size: file.size,
          path: file.path,
          name: file.name,
          bytes: file.bytes,
          readStream: file.readStream,
        ));
      }
      return true;
    }
    return false;
  }
}
